#encoding: utf-8

from flask import (
    Blueprint,
    request,
    make_response,
    jsonify
)
from exts import alidayu
from utils import restful, amancache
from utils.captcha import Captcha
import random
import config
from .forms import SMSCaptchaForm
from io import BytesIO
import qiniu



bp = Blueprint("common", __name__, url_prefix='/common')

# 短信不安全验证码
# @bp.route('/sms_captcha/')
# def sms_captcha():
#     telephone = request.args.get('telephone')
#     if not telephone:
#         return restful.params_error(message='请输入手机号')
#     # captcha = Captcha.gene_text(number=4) # 这个生成的验证码有英文
#     captcha = ''.join(random.sample(config.NUMLIST, 4))
#     print('sms_captcha= ',captcha)
#     if alidayu.send_sms(telephone, code=captcha):
#         return restful.success('验证码发送成功！')
#     else:
#         # return restful.params_error(message='验证码发送失败！')
#         return restful.success('假发送成功')

# 短信安全验证码
@bp.route('/sms_captcha/', methods = ['POST'])
def sms_captcha():
    form = SMSCaptchaForm(request.form)
    if form.validate():
        telephone = form.telephone.data
        captcha = ''.join(random.sample(config.NUMLIST, 4))
        print('sms_captcha= ',captcha)
        if alidayu.send_sms(telephone, code=captcha):
            amancache.set(telephone, captcha)
            return restful.success('验证码发送成功！')
        else:
            # amancache.set(telephone, captcha) # 上线时必须去掉该代码
            return restful.params_error(message='验证码发送失败！')
    else:
        return restful.params_error(message='参数错误！')

# 图形验证码
@bp.route('/captcha/')
def graph_captcha():
    # 获取验证码
    text, image = Captcha.gene_graph_captcha()
    amancache.set(text.lower(), text.lower(), timeout=120)
    # BYtesIO：字节流
    out = BytesIO()
    image.save(out, 'png')
    out.seek(0) # save后将指针设置到首位，不然会读取为空
    resp = make_response(out.read())
    resp.content_type = 'image/png'
    return resp

# 七牛
@bp.route('/uptoken/')
def uptoken():
    access_key = config.QN_CONF['access_key']
    secret_key = config.QN_CONF['secret_key']
    q = qiniu.Auth(access_key,secret_key)

    bucket = config.QN_CONF['bucket']
    token = q.upload_token(bucket)
    return jsonify({'uptoken':token})


